//
//  AliYunUtil.swift
//  kxf
//
//  Created by Mac on 2024/3/7.
//

import Foundation
import AliyunOSSiOS

typealias StringBoolCallback = (_ text:String, _ value:Bool) -> Void

class DSImageUploader {

    static let shared = DSImageUploader.init()

    let config = OSSClientConfiguration()

    let credantial = OSSFederationCredentialProvider { () -> OSSFederationToken? in
        let token = OSSFederationToken()
        token.tAccessKey = "LTAI5tMJEtBEeEiLacs2rMoF"//UserModel.shared.accessKeyId
        token.tSecretKey = "2JFe8K5KGkRPMEUK4twEhPoArIjJwY"//UserModel.shared.accessKeySecret
       return token
    }

    let client: OSSClient
    let endpoint = "https://oss-cn-beijing.aliyuncs.com"
    init() {

     OSSLog.enable()

     config.maxRetryCount = 2

     config.timeoutIntervalForRequest = 30

     config.timeoutIntervalForResource = 120

        client=OSSClient(endpoint:endpoint, credentialProvider:credantial, clientConfiguration:config)

    }
}

extension DSImageUploader {

    func uploadImages(_image:Data,imgType:String? = "", completionHandler:@escaping StringBoolCallback) {

        let interval = Date().todaySeconds
     let arcNum = Int.random(in: 1000...9999)
     let put = OSSPutObjectRequest()
     put.bucketName = "yukuaifu"
        put.objectKey="mall/images/ykfiOS_\(imgType ?? "")\(UserModel.shared.userId)\(interval)\(arcNum).png"
     put.uploadingData = _image
     put.uploadProgress = { bytesSent, totalByteSent, totalByteExpectedToSend in
        print(bytesSent, totalByteSent, totalByteExpectedToSend)
     }

     let putTask = client.putObject(put)

     putTask.continue({ (task:OSSTask) ->Any?in

         if task.error == nil{

             print("upload object success!")
             
             let str = self.endpoint.components(separatedBy:CharacterSet.init(charactersIn:"//")).last

             let url = String(format:"http://%@.%@/%@", put.bucketName, str!, put.objectKey)

             print("上传图片成功：", url)

             DispatchQueue.main.async{

                completionHandler(url, true)

             }

         }else{

             let error:NSError = (task.error)! as NSError

             print("图片上传错误：",error.description)

             completionHandler("", false)

         }

         return nil

         }).waitUntilFinished()

    }

}
